# -*-coding:utf-8-*-

import time
import json
from datetime import timedelta

from pyrestful import mediatypes
from pyrestful.rest import get, put

from utils.auth import authenticated
from handlers.base import BaseHandler


class DevicesServicesHandler(BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(DevicesServicesHandler, self).__init__(application, request, **kwargs)
        self.devices_dao = self.settings['daos']['devices']

    @authenticated
    @put(_path='/internal/api/devices/{device_id}/services/{service_name}', _types=[str, str],
         _produces=mediatypes.APPLICATION_JSON)
    def internal_update_device_service(self, device_id, service_name):
        if not self.is_owner_of_device(device_id):
            return
        db = self.settings['db']
        devices_services = db.get_collection('devices_services')

        request = json.loads(self.request.body)
        recharge_days = int(request['recharge_days'])
        recharge_seconds = int(timedelta(days=recharge_days).total_seconds())
        cur_time = int(time.time())

        # TODO: 考虑多进程并发情况/ZK LOCK
        result = devices_services.find_one({'device_id': device_id})
        if result is None:
            service = {}
            service['name'] = service_name
            service['expire_time'] = cur_time + recharge_seconds
            service['total_used_time'] = 0
            service['first_pay_time'] = cur_time
            service['last_pay_time'] = cur_time

            device = {}
            services = [service]
            device['device_id'] = device_id
            device['services'] = services

            devices_services.insert_one(device)
            self.respond_success()
        else:
            service_found = False
            i = 0
            for service in result['services']:
                if service['name'] == service_name:
                    if service['expire_time'] < cur_time:
                        service['total_used_time'] += service['expire_time'] - service['last_pay_time']
                    else:
                        service['total_used_time'] += cur_time - service['last_pay_time']
                    service['last_pay_time'] = cur_time
                    service['expire_time'] += recharge_seconds
                    service_found = True
                    devices_services.find_one_and_update({'device_id': device_id},
                                                         {'$set': {'services.%d' % i: service}})
                    break
                i = i + 1
            if not service_found:
                service = {}
                service['name'] = service_name
                service['expire_time'] = cur_time + recharge_seconds
                service['total_used_time'] = 0
                service['first_pay_time'] = cur_time
                service['last_pay_time'] = cur_time
                devices_services.find_one_and_update({'device_id': device_id}, {'$push': {'services': service}})
            self.respond_success()

    @authenticated
    @get(_path='/api/devices/{device_id}/services', _types=[str, str], _produces=mediatypes.APPLICATION_JSON)
    def retrieve_device_service_list(self, device_id):
        if not self.is_owner_of_device(device_id):
            return
        self.tmp_retrieve_device_service_list(device_id)

    # 供设备查询使用(临时接口)
    @get(_path='/tmp/api/devices/{device_id}/services', _types=[str, str], _produces=mediatypes.APPLICATION_JSON)
    def tmp_retrieve_device_service_list(self, device_id):
        db = self.settings['db']
        devices_services = db.get_collection('devices_services')
        services = []
        result = devices_services.find_one({'device_id': device_id})
        if result is not None:
            cur_time = int(time.time())
            services = result['services']
            for service in services:
                if service['expire_time'] < cur_time:
                    service['total_used_time'] += service['expire_time'] - service['last_pay_time']
                else:
                    service['total_used_time'] += cur_time - service['last_pay_time']
        self.respond_success(services)
